//
//  PlayViewController.m
//  WXMusic
//
//  Created by 漫步人生路 on 15/9/6.
//  Copyright (c) 2015年 漫步人生路. All rights reserved.
//

#import "PlayViewController.h"
#import "SongPicAndLrcView.h"
#import "SongsControlAndInfoView.h"
#import "PlayModel.h"
#import "LyricHelper.h"
#import "PlayTableViewCell.h"
#import "PlayerDataBase.h"
@interface PlayViewController ()<LouMusicDelegate,UITableViewDataSource,UITableViewDelegate>
{
    SongsControlAndInfoView *controlAndInfo;
}
@property (nonatomic, strong) BlurImageView *blurImageVC;
@property (nonatomic, strong) SongPicAndLrcView *songPicAndLrcVC;
//时间数组
@property (nonatomic, strong) NSMutableArray *timeArray;
//歌词数组
@property (nonatomic, strong)
    NSMutableArray *lyrcArray;
@end

@implementation PlayViewController
- (NSMutableArray *)timeArray
{
    if (!_timeArray) {
        _timeArray = [[NSMutableArray alloc]init];
    }
    return _timeArray;
}
- (NSMutableArray *)lyrcArray
{
    if (!_lyrcArray) {
        _lyrcArray = [[NSMutableArray alloc]init];
    }
    return _lyrcArray;
}

- (NSString *)setTimeWithInterval:(float)interval
{
    //分钟
    int minutes = interval / 60;
    //秒
    int seconds = (int)interval % 60;
    return [NSString stringWithFormat:@"%d:%02d",minutes,seconds];
}
- (void)audioManagerStreamer:(LouMusicPlayer *)streamer songProgress:(float)songProgress
{
    controlAndInfo.songProgress.value = songProgress;
    if ([[LouMusicPlayer shareMusicPlayer]isPlaying] == YES) {
        self.songPicAndLrcVC.songPicView.transform = CGAffineTransformRotate(self.songPicAndLrcVC.songPicView.transform, 0.01);
        //正在运行的时间
        controlAndInfo.starTime.text = [self setTimeWithInterval:songProgress];
        //剩余时间
        controlAndInfo.stopTime.text = [self setTimeWithInterval:controlAndInfo.songProgress.maximumValue - songProgress];
        for (int i = 0; i < self.timeArray.count
            ; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            NSString *timeString = [self setTimeWithInterval:[self.timeArray[i]floatValue]];
            if ([[self setTimeWithInterval:songProgress] isEqualToString:timeString]) {
                [self.songPicAndLrcVC.lrcView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];

            }
        }
    }else
    {
        
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadSongInfo) name:@"reload" object:nil];
    [[LouMusicPlayer shareMusicPlayer] reloadSong];
    [LouMusicPlayer shareMusicPlayer].louPlayerDelegate = self;
    self.blurImageVC = [[BlurImageView alloc]initWithFrame:kBounds];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self setUpBackButton:backButton];
    [self.blurImageVC addSubview:backButton];
    [self setUpSongPicAndLrcVC];
    [self setUpSongsControlAndInfoVC];
    [self.view addSubview:self.blurImageVC];
//    [self reloadSongInfo];
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(starPlay) name:@"readyToPlay" object:nil];
    
}

//请求并解析歌曲信息
- (void)reloadSongInfo
{
//    [[LouMusicPlayer shareMusicPlayer] playSongWithUrl:[LouMusicPlayer shareMusicPlayer].playModel.file_link];
    [controlAndInfo setUpSongName:[LouMusicPlayer shareMusicPlayer].playModel.title singeName:[LouMusicPlayer shareMusicPlayer].playModel.author];

    //设置进度条的最大值
    controlAndInfo.songProgress.maximumValue = [LouMusicPlayer shareMusicPlayer].playModel.file_duration.floatValue;
    //获取歌词
    [[LyricHelper lyricHelper] setSongLrcWithUrl:[LouMusicPlayer shareMusicPlayer].playModel.lrclink lycArray:self.lyrcArray timeArray:self.timeArray];
    //专辑图片赋值
    [self.songPicAndLrcVC setTaget:self image:[LouMusicPlayer shareMusicPlayer].playModel.pic_huge];
    self.songPicAndLrcVC.lrcView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.songPicAndLrcVC.lrcView registerClass:[PlayTableViewCell class] forCellReuseIdentifier:@"cell"];
    //模糊视图赋值
    [self.blurImageVC sd_setImageWithURL:[NSURL URLWithString:[LouMusicPlayer shareMusicPlayer].playModel.pic_huge]];
//    [LORequestManger GET:[[kPlayUrl stringByAppendingString:[[LouMusicPlayer shareMusicPlayer].modelArray objectAtIndex:[LouMusicPlayer shareMusicPlayer].index]] stringByAppendingString:kSongid] success:^(id response) {
//        NSDictionary *dic = (NSDictionary *)response;
//        PlayModel *playModel = [PlayModel shareJsonWithBitrate:dic[@"bitrate"] songInfo:dic[@"songinfo"]];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:nil];
//        [[LouMusicPlayer shareMusicPlayer] playSongWithUrl:playModel.file_link];
//        //设置进度条的最大值
//        controlAndInfo.songProgress.maximumValue = playModel.file_duration.floatValue;
//        //获取歌词
//        [[LyricHelper lyricHelper] setSongLrcWithUrl:playModel.lrclink lycArray:self.lyrcArray timeArray:self.timeArray];
//        //专辑图片赋值
//        [self.songPicAndLrcVC setTaget:self image:playModel.pic_huge];
//        self.songPicAndLrcVC.lrcView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        [self.songPicAndLrcVC.lrcView registerClass:[PlayTableViewCell class] forCellReuseIdentifier:@"cell"];
//        //模糊视图赋值
//        [self.blurImageVC sd_setImageWithURL:[NSURL URLWithString:playModel.pic_huge]];
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
//    }];
}
- (void)starPlay
{
    //开始播放
    [[LouMusicPlayer shareMusicPlayer] starPlaySong];
    //判断我们是否缓冲成功
    if ([[LouMusicPlayer shareMusicPlayer] readyToPlay] == YES) {
        //如果缓冲成功，给button重新设置一张图片
        //当我们的歌曲正在播放当中，我们的button默认图片应该为‘暂停’的图片
        //当我们的歌曲没有在播放，我们的button默认图片应该为'播放'的图片
        [controlAndInfo.playButton setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
    }
    NSLog(@"通知");
}

//设置歌曲图片与歌词页面
- (void)setUpSongPicAndLrcVC
{
    self.songPicAndLrcVC = [[SongPicAndLrcView alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - kHeight / 2.5)];
    [self.blurImageVC addSubview:self.songPicAndLrcVC];
}
//设置歌曲控制与展示视图
- (void)setUpSongsControlAndInfoVC
{
    controlAndInfo = [[SongsControlAndInfoView alloc]initWithFrame:CGRectMake(0, 55 + self.songPicAndLrcVC.bounds.size.height, kWidth, kHeight - 55 - self.songPicAndLrcVC.bounds.size.height)];
    //slider拖动事件
    [controlAndInfo.songProgress addTarget:self action:@selector(sliderSelector) forControlEvents:UIControlEventValueChanged];
    
    [controlAndInfo.playButton addTarget:self action:@selector(playSong) forControlEvents:UIControlEventTouchUpInside];
    controlAndInfo.playButton.tag = 1001;
    [controlAndInfo.nextButton addTarget:self action:@selector(nextSong) forControlEvents:UIControlEventTouchUpInside];
    [controlAndInfo.lastButton addTarget:self action:@selector(lastSong) forControlEvents:UIControlEventTouchUpInside];
    [controlAndInfo.playOrderButton addTarget:self action:@selector(playOrderWithSong) forControlEvents:UIControlEventTouchUpInside];
    [controlAndInfo.downloadButton addTarget:self action:@selector(downloadSong) forControlEvents:UIControlEventTouchUpInside];
    [self.blurImageVC addSubview:controlAndInfo];
}
//slider拖动事件，指定从某个时间点播放歌曲
- (void)sliderSelector
{
    [[LouMusicPlayer shareMusicPlayer] seekToTime:controlAndInfo.songProgress.value];
}

- (void)playSong
{
    controlAndInfo.playButton.tag += 1;
    int tag = (controlAndInfo.playButton.tag - 1000) % 2;
    if (tag == 0) {
        NSLog(@"暂停播放");
        [[LouMusicPlayer shareMusicPlayer] stopPlaySong];
        [controlAndInfo.playButton setImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
    }else
    {
        [[LouMusicPlayer shareMusicPlayer] starPlaySong];
        [controlAndInfo.playButton setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
        NSLog(@"开始播放");
    }
}

- (void)nextSong
{
    [[LouMusicPlayer shareMusicPlayer] playNextSong];
    
}
- (void)lastSong
{
    
}
- (void)playOrderWithSong
{
    
}
- (void)downloadSong
{

//        [[PlayerDataBase shareDataBase] createPlaySongListWithName:@"SongList"];
    [[PlayerDataBase shareDataBase] deleteCinemaModelWithSongID:[[LouMusicPlayer shareMusicPlayer].playModel.song_id integerValue]];
//        [[PlayerDataBase shareDataBase] insertModel:[LouMusicPlayer shareMusicPlayer].playModel];
}
//设置返回按钮
- (void)setUpBackButton:(UIButton *)backButton
{
    backButton.frame = CGRectMake(10, 25, 30, 30);
    [backButton setImage:[UIImage imageNamed:@"arrowdown"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backSongsVC) forControlEvents:UIControlEventTouchUpInside];
    [backButton setTintColor:[UIColor whiteColor]];

}

- (void)backSongsVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/**
 *  TableView
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.timeArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"forIndexPath:indexPath];
    cell.lyrcLabel.text = [self.lyrcArray objectAtIndex:indexPath.row];
    return cell;
}







@end
